package com.ruoyi.system.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.RedisConfig;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.InterfaceOperationLog;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import com.ruoyi.system.api.service.IUserService;
import com.ruoyi.system.api.service.PokeRequestServe;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
@Service
public class PokeRequestServeImpl implements PokeRequestServe
{

    private static final Logger log = LoggerFactory.getLogger(PokeRequestServeImpl.class);

    /** 配置文件 */
    @Autowired
    private Global global;

    /** redis配置文件 */
    @Autowired
    private RedisConfig redisConfig;

    /** 用户表 */
    @Autowired
    private IUserService iUserService;

    /** 接口调用日志 */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    /**
     * 发送get请求
     * @param faceUrl 接口请求路径
     * @param faceName 接口名称
     * @param faceType 接口类型
     * @author: wlf
     * @date: 2020/3/32 14:26
     * @return
     */
    public ResponseWithData transGet(String faceUrl, String faceName, String faceType) {
        String ccServerUrl = global.getCcServerUrl();

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName(faceName);
        interfaceOperationLog.setInterfaceType(faceType);
        interfaceOperationLog.setInterfaceUrl(faceUrl.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().getRequest(faceUrl.toString(), null);
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("error 调用CC端登录接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                return new ResponseWithData().success(interfaceResponseBody).msg("success").code(200);
            }
        }
        return new ResponseWithData().success().msg("error 调用CC端登录接口返回异常").code(201);
    }

    /**
     * 发送post请求
     * @param faceUrl 接口请求路径
     * @param faceName 接口名称
     * @param faceType 接口类型
     * @param params 请求参数
     * @author: wlf
     * @date: 2020/3/32 14:26
     * @return
     */
    public ResponseWithData transPost(String faceUrl, String faceName, String faceType, JSONObject params) {
        String ccServerUrl = global.getCcServerUrl();

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName(faceName);
        interfaceOperationLog.setInterfaceType(faceType);
        interfaceOperationLog.setInterfaceUrl(faceUrl.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(faceUrl, params);
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("error 调用CC端登录接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                return new ResponseWithData().success(interfaceResponseBody).msg("success").code(200);
            }
        }
        return new ResponseWithData().success().msg("error 调用CC端登录接口返回异常").code(201);
    }

    /**
     * 发送post请求
     * @param faceUrl 接口请求路径
     * @param faceName 接口名称
     * @param faceType 接口类型
     * @param params 请求参数
     * @author: wlf
     * @date: 2020/3/26 10:01
     * @return
     */
    public ResponseWithData transPost(String faceUrl, String faceName, String faceType, String params) {
        String ccServerUrl = global.getCcServerUrl();

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName(faceName);
        interfaceOperationLog.setInterfaceType(faceType);
        interfaceOperationLog.setInterfaceUrl(faceUrl.toString());
        interfaceOperationLog.setStartTime(new Date());
       // interfaceOperationLog.setInterfaceRequest(params.toString());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(faceUrl, params);
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        //图片过大进行处理
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("error 调用CC端登录接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                return new ResponseWithData().success(interfaceResponseBody).msg("success").code(200);
            }
        }
        return new ResponseWithData().success().msg(interfaceResponse).code(201);
    }

    
    public ResponseWithData transPostNew(String faceUrl, String faceName, String faceType, String params) {
        String ccServerUrl = global.getCcServerUrl();

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName(faceName);
        interfaceOperationLog.setInterfaceType(faceType);
        interfaceOperationLog.setInterfaceUrl(faceUrl.toString());
        interfaceOperationLog.setStartTime(new Date());
        interfaceOperationLog.setInterfaceRequest(params.toString());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(faceUrl, params);
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        //图片过大进行处理
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            return new ResponseWithData().success().msg("error 调用CC端登录接口发生异常").code(202);
        }
        if(res!=null) {
            if (res.code() == 200) {
                return new ResponseWithData().success(interfaceResponseBody).msg("success").code(200);
            }
        }
        return new ResponseWithData().success().msg("error 调用CC端登录接口返回异常").code(201);
    }

    
    /**
     * 发送post请求
     * @param faceUrl 接口请求路径
     * @param faceName 接口名称
     * @param faceType 接口类型
     * @param params 请求参数
     * @author: wlf
     * @date: 2020/3/26 10:01
     * @return
     */
    public Map<String, String> transPostJD(String faceUrl, String faceName, String faceType, String params) {
        Map<String, String> result = new HashMap<>();
        String ccServerUrl = global.getCcServerUrl();

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName(faceName);
        interfaceOperationLog.setInterfaceType(faceType);
        interfaceOperationLog.setInterfaceUrl(faceUrl.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(faceUrl, params);
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数："+interfaceResponseBody;
            log.info("调用CC端返回结果："+interfaceResponseBody);
            if(res.code() == 200){
                interfaceState = "1";
            }else {
                interfaceState = "2";
            }
        }catch (Exception e){
            log.info("调用CC端返回结果："+interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if("0".equals(interfaceState)){
            result.put("code","202");
            result.put("msg","error 调用CC端接口发生异常");
        }
        if(res!=null) {
            if (res.code() == 200) {
                result.put("code", "200");
                result.put("msg", "success");
                result.put("responseBody", interfaceResponseBody);
            } else {
                result.put("code", "201");
                result.put("msg", "error 调用CC端接口返回异常");
            }
        }
        return result;
    }

    /**
     * 拼参数
     * @param paramInfo 实体对象
     * @author: wlf
     * @date: 2020/3/29 22:32
     * @return
     */
    public String spellPrams(Object paramInfo) throws Exception{
        StringBuffer param = new StringBuffer("");
        Field[] fields = paramInfo.getClass().getDeclaredFields();
        for (int i = 0 ; i < fields.length; i ++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (field.getName().equals("Doa_pic")) {//备件还货图片路径不在此处拼接
                continue;
            }
            if (i > 0) {
                param.append("&");
            }
            param.append(field.getName()).append("=").append(field.get(paramInfo) == null ? "" : field.get(paramInfo));
        }
//        System.out.println( param.toString());
        return param.toString();
    }
}
